<template>
  <div>
    <el-dialog
      v-loading="loading"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      title="SKU管理"
      fullscreen
      center
      @close="close"
    >
      <div v-if="row" class="sku-container">
        <!-- 商品信息 -->
        <!-- <div>
          <div>{{row.goods.title}}</div>
          <div>
            <span v-if="row.goods.category.length===0">无归属分类</span>
            <span v-for="(attr,attrIndex) in row.goods.category" :key="attrIndex">
              {{attr}}
              <span v-if="attrIndex+1!==row.goods.category.length">/</span>
            </span>
          </div>
          <div>{{goodsTypeOptions[row.goods.goodsType]}}}</div>
        </div>-->
        <div class="goods-info-box flexRSC">
          <div class="cover-img">
            <img
              v-if="row.goods.coverImg"
              :src="fileBaseUrl + row.goods.coverImg"
              alt
              srcset
            >
          </div>
          <div>
            <div class="goods-title app-line-two">{{ row.goods.title }}</div>
            <div class="goods-detail app-line-two">
              <span v-if="row.goods.category.length === 0">无归属分类</span>
              <span
                v-for="(attr, attrIndex) in row.goods.category"
                :key="attrIndex"
              >
                {{ attr }}
                <span
                  v-if="attrIndex + 1 !== row.goods.category.length"
                >/</span>
              </span>
            </div>
            <div class="goods-detail app-line-two">
              {{ goodsTypeOptions[row.goods.goodsType] }}
            </div>
          </div>
        </div>
        <!-- sku信息 -->
        <div class="sku-info-box">
          <div class="sku-title">
            <span v-if="row.skuInfo.specAttrNameList.length === 0">无属性</span>
            <span
              v-for="(attr, attrIndex) in row.skuInfo.specAttrNameList"
              :key="attrIndex"
            >
              {{ attr }}
              <span
                v-if="attrIndex + 1 !== row.skuInfo.specAttrNameList.length"
              >/</span>
            </span>
          </div>
          <div class="sku-price">
            <span>市场价：￥ {{ row.skuInfo.originPrice / 100 }}</span>
            <span>参考售价：￥ {{ row.skuInfo.price / 100 }}</span>
            <span>
              sku状态：
              <el-tag :type="row.skuInfo.status ? '' : 'danger'" size="small">{{
                statusOptions[row.skuInfo.status]
              }}</el-tag>
            </span>
          </div>
        </div>
        <!-- 价格库存管理 -->
        <div class="handle-tablle-btn">
          <el-button
            :disabled="!checkStoreIds.length"
            type="text"
            @click="changeBatchStatus(1)"
          >批量启用</el-button>
          <el-button
            :disabled="!checkStoreIds.length"
            type="text"
            @click="changeBatchStatus(0)"
          >批量关闭</el-button>
          <el-button
            :disabled="!checkStoreIds.length"
            type="text"
            @click="changeBatchPrice"
          >批量设价格</el-button>
          <el-button
            :disabled="!checkStoreIds.length"
            type="text"
            @click="changeBatchStock('add')"
          >批量增库存</el-button>
          <el-button
            :disabled="!checkStoreIds.length"
            type="text"
            @click="changeBatchStock('reduce')"
          >批量减库存</el-button>
        </div>
        <el-form ref="form" :model="form" label-width="100px" size="small">
          <el-table
            ref="multipleTable"
            :data="form.list"
            border
            stripe
            style="width: 100%"
            size="small"
            empty-text="暂无数据"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" fixed="left" />
            <el-table-column prop="storeName" label="店铺" />
            <el-table-column prop="status" label="店铺在售">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  :active-value="1"
                  :nactive-value="0"
                  @change="(val) => changeSingleStatus(val, scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="price" label="销售价格/元">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'list.' + scope.$index + '.price'"
                  :rules="rules.price"
                  label-width="0"
                  class="m-t-18"
                >
                  <el-input
                    v-model.trim="scope.row.price"
                    class="w-120"
                    placeholder="请输入价格"
                    @change="(val) => changeSinglePrice(val, scope.row)"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="inventory" label="库存" />
            <el-table-column prop="stockMode" label="设置库存" width="280">
              <template slot-scope="scope">
                <el-form-item label-width="0" class="m-t-18">
                  <el-select v-model="scope.row.stockMode" class="w-120">
                    <el-option label="增加库存" value="add" />
                    <el-option label="减少库存" value="reduce" />
                  </el-select>
                </el-form-item>
                <el-form-item
                  :prop="'list.' + scope.$index + '.stockNum'"
                  :rules="rules.stockNum"
                  label-width="0"
                  class="m-t-18"
                >
                  <el-input
                    v-model.trim="scope.row.stockNum"
                    class="w-120"
                    placeholder="请输入数量"
                    @change="(val) => changeSingleStock(val, scope.row)"
                  />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  productSkuStoreList,
  productSkuDetailByShop,
  modifyProductSkuStock,
  modifyProductSkuState
} from '@/views/wxaMallModule/api/sku'
import {
  validateCustomTwoDecimal,
  validateCustomPositiveInt
} from '@/utils/validate'
import { mapGetters } from 'vuex'
export default {
  data() {
    // 价格管理
    const validatorPrice = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入价格'))
      } else if (!validateCustomTwoDecimal(value, 7)) {
        callback(new Error('范围0.01~9999999.99'))
      } else {
        callback()
      }
    }
    //  库存管理
    const validatorStockNum = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!validateCustomPositiveInt(value, 7)) {
        callback(new Error('范围1~9999999'))
      } else {
        callback()
      }
    }
    return {
      // 校验字段相关
      rules: {
        price: [
          {
            required: true,
            validator: validatorPrice,
            trigger: ['blur', 'change']
          }
        ],
        stockNum: [
          {
            required: true,
            validator: validatorStockNum,
            trigger: ['blur', 'change']
          }
        ]
      },
      // 配置
      resolve: null,
      reject: null,
      goodsTypeOptions: {
        100: '实物商品',
        101: '配件商品',
        200: '卡/券包'
        // 300: "同城配送",
      },
      statusOptions: {
        0: '已下架',
        1: '已上架'
      },
      // 状态
      dialogVisible: null,
      loading: false,
      // 数据
      row: null,
      storeId: null,
      storeName: null,
      checkStoreIds: [],
      lastCheckStoreIds: [],
      form: {
        list: []
      }
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl'])
  },
  methods: {
    /**
       * 弹框相关
       */
    open({ row, storeId = null, storeName = null }) {
      this.loading = true
      this.row = JSON.parse(JSON.stringify(row))
      this.storeId = storeId
      this.storeName = storeName
      this.getSkuInfo()
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      this.loading = false
      this.form.list = []
      this.checkStoreIds = []
      this.resolve && this.resolve()
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    /**
       * 数据组
       */

    // 获取sku列表 多店铺
    getSkuInfo() {
      this.lastCheckStoreIds = this.checkStoreIds
      if (this.storeId) {
        const params = {
          skuId: this.row.skuInfo.skuId,
          storeId: this.storeId
        }
        productSkuDetailByShop(params)
          .then((res) => {
            const data = res.data
            console.log(data)
            const obj = {
              inventory: data.skuDetail.storeInventory,
              price:
                  data.skuDetail.storePrice == -1 || !data.skuDetail.storePrice
                    ? this.row.skuInfo.price / 100
                    : data.skuDetail.storePrice / 100,
              skuId: data.skuDetail.skuInfo.skuId,
              status: data.skuDetail.storeStatus,
              storeId: this.storeId,
              storeName: this.storeName,
              stockMode: 'add',
              stockNum: null
            }
            this.form.list = [obj]
            this.initCheckbox()
          })
          .catch((err) => {})
          .finally(() => {
            this.loading = false
          })
      } else {
        productSkuStoreList({ skuId: this.row.skuInfo.skuId })
          .then((res) => {
            res.data.forEach((v) => {
              v.price =
                  v.price == -1 || !v.price
                    ? this.row.skuInfo.price / 100
                    : v.price / 100
              v.stockMode = 'add'
              v.stockNum = null
            })
            this.form.list = res.data
            this.initCheckbox()
          })
          .catch((err) => {})
          .finally(() => {
            this.loading = false
          })
      }
    },

    /**
       * 按钮组
       */
    // 编辑价格&状态
    modifyPrice(params) {
      this.loading = true
      modifyProductSkuState(params)
        .then((res) => {
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000,
            offset: 40
          })
          this.getSkuInfo()
        })
        .catch((err) => {})
        .finally(() => {
          this.loading = false
        })
    },

    // 修改状态单个
    changeSingleStatus(value, row) {
      const params = {
        skuId: row.skuId,
        status: value ? 1 : 0,
        storeIdList: [row.storeId]
      }
      this.modifyPrice(params)
    },

    // 批量状态
    changeBatchStatus(status) {
      const params = {
        skuId: this.row.skuInfo.skuId,
        status: status,
        storeIdList: this.checkStoreIds
      }
      this.modifyPrice(params)
    },

    // 修改价格单个
    changeSinglePrice(value, row) {
      if (!validateCustomTwoDecimal(value, 7)) {
        return
      }
      const params = {
        skuId: row.skuId,
        price: this.$math.mul(value, 100, 0),
        storeIdList: [row.storeId]
      }
      this.modifyPrice(params)
    },

    // 修改价格批量
    changeBatchPrice() {
      const _this = this
      this.$prompt('请输入销售价格/元', '修改销售价格', {
        confirmButtonText: '保存',
        cancelButtonText: '取消',
        inputValidator: this.validatePrice
      })
        .then(({ value }) => {
          const params = {
            skuId: _this.row.skuInfo.skuId,
            price: _this.$math.mul(value, 100, 0),
            storeIdList: _this.checkStoreIds
          }
          _this.modifyPrice(params)
        })
        .catch(() => {})
    },

    // 校验价格
    validatePrice(val) {
      console.log(val)
      if (!val) {
        return '请输入价格'
      } else if (!validateCustomTwoDecimal(val, 7)) {
        return '请输入0.01~9999999.99范围金额（小数位不超过2位）'
      }
    },

    // 编辑库存
    modifyStock(params) {
      this.loading = true
      modifyProductSkuStock(params)
        .then((res) => {
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000,
            offset: 40
          })
          this.getSkuInfo()
        })
        .catch((err) => {})
        .finally(() => {
          this.loading = false
        })
    },

    // 修改库存 单个
    changeSingleStock(value, row) {
      if (!validateCustomPositiveInt(value, 7)) {
        return
      }
      const params = {
        skuId: this.row.skuInfo.skuId,
        num: row.stockMode === 'add' ? value : -value,
        storeIdList: [row.storeId]
      }
      this.modifyStock(params)
    },

    // 增加库存 批量
    changeBatchStock(mode) {
      const _this = this
      this.$prompt(
        `请输入${mode === 'add' ? '增加' : '减少'}库存数量`,
        `${mode === 'add' ? '增加' : '减少'}库存数量`,
        {
          confirmButtonText: '保存',
          cancelButtonText: '取消',
          inputValidator: this.validateStock
        }
      )
        .then(({ value }) => {
          const params = {
            skuId: _this.row.skuInfo.skuId,
            num: mode === 'add' ? value : -value,
            storeIdList: _this.checkStoreIds
          }
          _this.modifyStock(params)
        })
        .catch(() => {})
    },

    // 校验增加的库存
    validateStock(val) {
      if (!val) {
        return '请输入数量'
      } else if (!validateCustomPositiveInt(val, 6)) {
        return '请输入正整数（最大值999999）'
      }
    },

    /**
       * 状态组
       */
    // 初始化勾选按钮
    initCheckbox() {
      const _this = this
      if (this.lastCheckStoreIds.length == 0) return
      this.$nextTick(() => {
        _this.form.list.forEach((v) => {
          if (_this.lastCheckStoreIds.includes(v.storeId)) {
            _this.$refs.multipleTable.toggleRowSelection(v)
          } else {
            _this.$refs.multipleTable.clearSelection()
          }
        })
      })
    },

    // 多选状态栏改变
    handleSelectionChange(rows) {
      if (rows) {
        const ids = []
        rows.map((item) => {
          ids.push(item.storeId)
        })
        this.checkStoreIds = ids
      }
    }

    /**
       * 方法组
       */
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .sku-container {
    min-width: 900px;
  }
  .w-120 {
    width: 120px;
  }
  .m-t-18 {
    margin-top: 18px;
  }
  .el-form-item {
    display: inline-block;
  }

  /* 商品内容 */
  .goods-info-box {
    margin-bottom: 20px;
    .cover-img {
      margin-right: 20px;
      width: 80px;
      height: 80px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
    }
    .goods-title {
      font-size: 20px;
      font-weight: bold;
      color: #000;
    }
    .goods-detail {
      margin-top: 10px;
      font-size: 12px;
    }
  }

  .sku-info-box {
    margin-bottom: 20px;
    .sku-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 10px;
      color: #000;
    }
    .sku-price {
      font-size: 14px;
      span {
        margin-right: 20px;
      }
    }
  }
</style>
